﻿using System.Collections.Generic;

namespace ZFramework.Runtime
{
    public partial class EntityMgr
    {
        private class EntityInfo : IReference
        {
            private Entity _entity;
            private Entity _parentEntity;
            private List<Entity> _childEntities;
            private EntityStatus _status;

            public EntityInfo()
            {
                _entity = null;
                _parentEntity = null;
                _childEntities = new List<Entity>();
            }

            public void Clear()
            {
                _entity = null;
                _parentEntity = null;
                _childEntities.Clear();
            }

            public Entity Entity => _entity;

            public Entity ParentEntity
            {
                get => _parentEntity;
                set => _parentEntity = value;
            }

            public EntityStatus Status
            {
                get { return _status; }
                set { _status = value; }
            }

            public int ChildEntityCount
            {
                get { return _childEntities.Count; }
            }

            public Entity GetChildEntity()
            {
                return _childEntities.Count > 0 ? _childEntities[0] : null;
            }

            public Entity[] GetChildEntities()
            {
                return _childEntities.ToArray();
            }

            public void GetChildEntities(List<Entity> results)
            {
                if (results == null)
                {
                    return;
                }

                results.Clear();
                foreach (Entity childEntity in _childEntities)
                {
                    results.Add(childEntity);
                }
            }

            public void AddChildEntity(Entity childEntity)
            {
                if (_childEntities.Contains(childEntity))
                {
                    Log.Error("重复add child entity");
                    return;
                }

                _childEntities.Add(childEntity);
            }

            public void RemoveChildEntity(Entity childEntity)
            {
                if (!_childEntities.Remove(childEntity))
                {
                    Log.Error("尝试删除不存在的child entity");
                }
            }

            public static EntityInfo Create(Entity entity)
            {
                if (entity == null)
                {
                    Log.Error("entity 为null");
                    return null;
                }

                EntityInfo entityInfo = ReferencePool.Acquire<EntityInfo>();
                entityInfo._entity = entity;
                return entityInfo;
            }
        }
    }
}
